package com.jackspace.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.meidusa.fastjson.JSON;

@RestController
public class PicController {

	private final Logger logger = Logger.getLogger(getClass());

	@Autowired
	private DiscoveryClient client;

	private final DateFormat format = new SimpleDateFormat("yyyy-MM");

	@Value("${fileBase}")
	private String fileBase;
	
	@Value("${host}")
	private String host;

	@RequestMapping(value = "/uploadPic", method = RequestMethod.POST)
	public String uploadPic(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) 
	{
		ServiceInstance instance = client.getLocalServiceInstance();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try 
		{
			if (file == null)
			{
				resultMap.put("success", false);
				resultMap.put("message", "文件不能为空");
				return JSON.toJSONString(resultMap);
			}
			
			Date now = new Date();
	
			String fileName = file.getOriginalFilename();
			String monthPath = format.format(now);
			String path = fileBase + monthPath;
	
			File targetDir = new File(path);
			if (!targetDir.exists()) {
				targetDir.mkdirs();
			}
	
			String fullFileName = now.getTime() + "_" + fileName;
			File targetrFile = new File(path + "/" + fullFileName);
	
			file.transferTo(targetrFile);

			logger.info("/uploadPic, host:" + instance.getHost() + ", service_id:"
					+ instance.getServiceId());
			resultMap.put("success", true);
			resultMap.put("message", host + "/show/" + monthPath + "/" + fullFileName);
		}
		catch (Exception e) 
		{
			logger.error("uploadPic error:", e);
			resultMap.put("success", false);
		}
		
		return JSON.toJSONString(resultMap);

	}

	@RequestMapping(value = "/show/{month}/{fileName}.{subfix}", method = RequestMethod.GET)
	public void show(
			@PathVariable("month") String month,
			@PathVariable("fileName") String fileName,
			@PathVariable("subfix") String subfix,
			HttpServletRequest request, HttpServletResponse response) {
		ServiceInstance instance = client.getLocalServiceInstance();
		FileInputStream input = null;
		OutputStream os = null;
		try {
			input = new FileInputStream(fileBase + "\\" + month + "\\"
					+ fileName + "." + subfix);
			os = response.getOutputStream();// 取得输出流
			response.reset();// 清空输出流
			/**
			 * 根据实际运行效果 设置缓冲区大小
			 */
			byte[] buffer = new byte[1024];
			int ch = 0;
			while ((ch = input.read(buffer)) != -1) {
				os.write(buffer, 0, ch);
			}
			os.flush();

		} catch (FileNotFoundException e) {
			logger.error("show pic error:", e);
		} catch (IOException e) {
			logger.error("show pic error:", e);
		} finally {
			if (input != null)
			{
				try {
					input.close();
				} catch (IOException e) {
					logger.error("show pic input close error:", e);
				}
			}
			
			if (os != null)
			{
				try {
					os.close();
				} catch (IOException e) {
					logger.error("show pic os close error:", e);
				}
			}
		}

		logger.info("/show, host:" + instance.getHost() + ", service_id:"
				+ instance.getServiceId());

	}
}
